/*******************************************************************************
 * Copyright 2011, 2012 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.wzm.moviepic.fragment;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.view.ActionBarView;
import com.wzm.bean.HistoryBean;
import com.wzm.bean.MovieInfo;
import com.wzm.bean.PicInfo;
import com.wzm.cache.ConfigCache;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.manager.Tag;
import com.wzm.moviepic.R;
import com.wzm.moviepic.weight.HackyViewPager;
import com.wzm.moviepic.weight.ScrollTextView;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;
import com.wzm.utils.UILoadTools;
import com.wzm.utils.UtilsTools;

/**
 * 电影图片展示页面
 * @author zhengzhiyou
 */

public class ViewPagerActivity extends Activity{

	private ViewPager mViewPager;
	private SamplePagerAdapter spAdapter;
	
	private ArrayList<PicInfo> pList = new ArrayList<PicInfo>();
	private FinalHttp fh = null;
	
	//private static FinalBitmap fb = null;
	
	private Context mContext;
	private String movieid;
	private MovieInfo movieinfo;
	
	//显示图片页码
	private TextView tv_pageshow;
	
	
	
	
	private LinearLayout lly_head;
	private Button btn_back;
	private TextView tv_moviename;
	
	
	
	//行数
	private TextView tv_numline;
	private ScrollTextView tv_mmIntro;	
	private TextView mMovieIntro;
	private int numlines = 0;
	private int curLine = 0;
	
	//private int curPos = 0;
	//private int mTvWidth = 0;//获取它的宽度
	//获取分行以后的字符集
	//private ArrayList<String> curMessageList = null;
	//当前页
	
	private Button btn_readall = null;
	
	private int curPage = 0;	
	private long historyid = 0;
	
	private LinearLayout lly_botmintro;
	private LinearLayout lly_bottom;
	//private LinearLayout lly_center;
	//private AdView adView = null;
	
	
	
	private SeekBar mSeekBar;
	private TextView mSeekShow;
	
	//底部渐现
	private Animation animation = null;
	//底部渐隐
	private Animation animation1 = null;
	//头部出现
	private Animation head_in = null;
	
	//头部隐藏
	private Animation head_out = null;
	
	private LinearLayout lly_xdown = null;
	//广告
	//private AdsMogoLayout adsMogoLayout;
	private UMImage umimg = null;
	private UMSocialService controller = null;

	//2013-8-19 modify
	private LinearLayout lly_left = null;
	private LinearLayout lly_right = null;
	
	private LinearLayout rly_share = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		
		movieinfo = (MovieInfo)getIntent().getSerializableExtra("movieinfo");
		movieid = movieinfo.getId();
		
		pList.clear();
		//mViewPager = new HackyViewPager(this);
		setContentView(R.layout.activity_viewpager);
		mViewPager = (HackyViewPager)findViewById(R.id.viewpager);
		
		tv_pageshow = (TextView)findViewById(R.id.pageshow);
		
		animation = AnimationUtils.loadAnimation(this, R.anim.fadeout);
		animation1 = AnimationUtils.loadAnimation(this, R.anim.fadein);
		
		head_in  = AnimationUtils.loadAnimation(this, R.anim.headerin);
		head_out = AnimationUtils.loadAnimation(this, R.anim.headerout);

		
		lly_head = (LinearLayout)findViewById(R.id.movie_head);
		
		lly_bottom = (LinearLayout)findViewById(R.id.movieinfo_bottom_bar);
		
		lly_botmintro = (LinearLayout)findViewById(R.id.lly_botmintro_bar);
		
		//请求广告////////////////////////////////////////////////////////
//		lly_center = (LinearLayout)findViewById(R.id.lly_ad);
//		AdsMogoLayout adsMogoLayoutCode = new AdsMogoLayout(this, "7f8bfa79a54a42018c1b195dfbb56a1c",true);
//		lly_center.addView(lly_center);
		
		//添加观看次数
		AppManager.getInstance(mContext).getPlayedList().add(movieid);
		
		
		//aml.setAdsMogoListener(this);
		
		mSeekBar = (SeekBar)findViewById(R.id.movies_seekbar);
		mSeekShow = (TextView)findViewById(R.id.mSeekShow);
		
		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			//拖动完成事件
			@Override
			public void onStopTrackingTouch(SeekBar sb) {
				// TODO Auto-generated method stub
				mViewPager.setCurrentItem(sb.getProgress());
				
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				//showpagelable(arg1);
				tv_pageshow.setText((arg1)+"/"+(pList.size()));
				mSeekShow.setText((arg1)+"/"+(pList.size()));
			}
		});
		
		//注册更新广播
		IntentFilter intentFilter = new IntentFilter(Tag.OMUPDATEUI);
		registerReceiver(onMeasureBroadcastReceiver , intentFilter);
		
		
		
		//获取历史
		getHistory();
		
		spAdapter = new SamplePagerAdapter(mContext,pList,movieid);
		

		
		tv_mmIntro = (ScrollTextView)findViewById(R.id.movie_intro);
		tv_numline = (TextView)findViewById(R.id.tv_numline);
		mMovieIntro = (TextView)findViewById(R.id.mMovieIntro);
		
		mMovieIntro.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(numlines!=0)
				{
					++curLine;
					int numline = curLine%numlines;
					mMovieIntro.setText(tv_mmIntro.getLineString(numline));
					tv_numline.setText((numline+1)+"/"+numlines);	
				}	
			}
		});
		
		mViewPager.setAdapter(spAdapter);
		//请求数据
		fh = AppManager.getInstance(mContext).getFh();
		AjaxParams params = new AjaxParams();
		params.put("movieid",movieid);
		//Logger.error(movieid);
		//先进行缓存获取
        String cacheMoviePics = ConfigCache.getUrlCache(AppConfig.GETMOVIEINFO+movieid);
        if(cacheMoviePics==null)
        {
        	fh.post(AppConfig.GETMOVIEINFO, params,new AjaxCallBack<Object>() {

    			@Override
    			public AjaxCallBack<Object> progress(boolean progress, int rate) {
    				// TODO Auto-generated method stub
    				return super.progress(progress, rate);
    			}

    			@Override
    			public void onStart() {
    				// TODO Auto-generated method stub
    				UILoadTools.showLoading(ViewPagerActivity.this, "数据载入中");
    			}

    			@Override
    			public void onLoading(long count, long current) {
    				// TODO Auto-generated method stub
    				super.onLoading(count, current);
    			}

    			@Override
    			public void onSuccess(Object t) {
    				// TODO Auto-generated method stub
    				String content = (String)t;	   				
    				excuteJson(content);   				
    				UILoadTools.stopLoading();
    			}

    			@Override
    			public void onFailure(Throwable t, String strMsg) {
    				// TODO Auto-generated method stub
    				Toast.makeText(mContext, strMsg, Toast.LENGTH_SHORT).show();
    				UILoadTools.stopLoading();
    			}
    			
    		});
        }else{
        	excuteJson(cacheMoviePics);
        }
		
        

		
		
		
		btn_back = (Button)findViewById(R.id.btn_movieback);
		btn_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		tv_moviename = (TextView)findViewById(R.id.movie_name);
		tv_moviename.setText(movieinfo.getName());
		
		
		
	    
	    
	    
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				//Logger.info("onPageSelected:"+position);
				curPage = position;				
				numlines = 0;	
			    curLine = 0;				
				showpagelable(position);
				
				if(lly_head.getVisibility()!=View.GONE)
				{
					hidelly(position);
				}
				
				if(curPage==pList.size()-1)
				{
					lly_left.setVisibility(View.GONE);
					lly_right.setVisibility(View.GONE);
				}else{
					lly_left.setVisibility(View.VISIBLE);
					lly_right.setVisibility(View.VISIBLE);
				}
				
				
				

			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		//阅读全部
		btn_readall = (Button)findViewById(R.id.btn_readall);
		btn_readall.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub				
				
				if(numlines!=0)
				{
					++curLine;
					int numline = curLine%numlines;
					mMovieIntro.setText(tv_mmIntro.getLineString(numline));
					tv_numline.setText((numline+1)+"/"+numlines);	
				}	
				
			}
		});
		
		
		int isFirst = UtilsTools.getTagInt(this, Tag.ISREADFIRST);
        if(isFirst==0)
        {
        	showDialog();
        }
        
        
        lly_xdown = (LinearLayout)findViewById(R.id.lly_xdown);
        lly_xdown.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(curPage<=pList.size()-1)
				{
					PicInfo pi = pList.get(curPage);
					final String savePath = Environment.getExternalStorageDirectory().getPath()+"/MoviePic/";
					String filename =  pi.getImage().substring(pi.getImage().lastIndexOf("/")+1);
					fh.download(pi.getImage(), savePath+filename, new AjaxCallBack<File>() {

						@Override
						public void onStart() {
							// TODO Auto-generated method stub
							//super.onStart();
							Toast.makeText(mContext, "开始下载", Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onSuccess(File t) {
							// TODO Auto-generated method stub
							//super.onSuccess(t);
							Toast.makeText(mContext, "下载完成:"+savePath, Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onFailure(Throwable t, String strMsg) {
							// TODO Auto-generated method stub
							//super.onFailure(t, strMsg);
							Toast.makeText(mContext, "下载失败 |-_-|"+strMsg, Toast.LENGTH_SHORT).show();
						}
						
					});
				}else{
					Toast.makeText(mContext, "下载失败 |-_-|", Toast.LENGTH_SHORT).show();
				}				
			}
		});
        
        //2013-8-19 modify
        lly_left = (LinearLayout)findViewById(R.id.lly_left);
        lly_left.setOnClickListener(new OnClickListener() {
			//上一页
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(curPage-1>=0&&curPage!=pList.size()-1)
				{
					curPage = curPage-1;
					mViewPager.setCurrentItem(curPage,true);
				}
			}
		});
        
        
        lly_right = (LinearLayout)findViewById(R.id.lly_right);
        lly_right.setOnClickListener(new OnClickListener() {
			//下一页
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(curPage+1<pList.size())
				{
					curPage = curPage+1;
					mViewPager.setCurrentItem(curPage,true);
				}
			}
		});
        //获取推荐电影
        //getTjMovie();
        showlly();
		
        
        
        if(NetworkUtils.getNetworkState(mContext)!=NetworkUtils.NETWORN_NONE)
        {
        	 //社会化分享
            rly_share = (LinearLayout)findViewById(R.id.share_bar);
            //创建ActionBar des参数是ActionBar的唯一标识，请确保不为空
            ActionBarView socializeActionBar = new ActionBarView(mContext,movieinfo.getId());
            
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            socializeActionBar.setLayoutParams(layoutParams);
            //添加ActionBar
            rly_share.addView(socializeActionBar);
            
            
            String share_content = AppConfig.SHARE_CONTENT.replaceAll("#电影名#", movieinfo.getName());
			controller = UMServiceFactory.getUMSocialService(movieinfo.getId(),RequestType.SOCIAL);
			//设置分享文字
			controller.setShareContent(share_content);
			umimg = new UMImage(mContext, movieinfo.getBpic());
			controller.setShareImage(umimg);
        }
       
	}
	
	
	
	
	
	public void touchview()
	{
		if(lly_bottom.getVisibility()==View.GONE)
		{
			showlly();
		}else{
			hidelly();
		}
	}
	
	
	
	
	
	public void showlly()
	{
		
		lly_botmintro.startAnimation(animation);
		lly_botmintro.setVisibility(View.GONE);
		
		lly_bottom.startAnimation(animation1); 
		lly_head.startAnimation(head_in); 
		lly_bottom.setVisibility(View.VISIBLE);
		lly_head.setVisibility(View.VISIBLE);
	
		
		
	}
	
	public void hidelly()
	{
		
		lly_botmintro.startAnimation(animation1);
		lly_botmintro.setVisibility(View.VISIBLE);
		
		lly_bottom.startAnimation(animation); 
		lly_head.startAnimation(head_out); 
		lly_bottom.setVisibility(View.GONE);
		lly_head.setVisibility(View.GONE);
	}
	
	
	public void hidelly(int position)
	{
		if(position!=pList.size()-1)
		{
			lly_botmintro.startAnimation(animation1);
			lly_botmintro.setVisibility(View.VISIBLE);
		}
		
		
		
		lly_bottom.startAnimation(animation); 
		lly_head.startAnimation(head_out); 
		lly_bottom.setVisibility(View.GONE);
		lly_head.setVisibility(View.GONE);
	}
	
	
	public void excuteJson(String rejson)
	{
		pList.clear();
		try {
			JSONObject result = new JSONObject(rejson);
			int status = result.getInt("status");
			if(status==1)
			{
				ConfigCache.setUrlCache(rejson, AppConfig.GETMOVIEINFO+movieid);    
				JSONArray list = result.getJSONArray("story");
				for(int i=0;i<list.length();i++)
				{
					JSONObject obj = list.getJSONObject(i);
					PicInfo pinfo = new PicInfo();
					pinfo.setId(obj.getString("id"));
					pinfo.setImage(obj.getString("image"));
					pinfo.setIntro(obj.getString("intro"));
					pinfo.setpIndex(obj.getString("pindex"));
					pList.add(pinfo);
				}
				
				pList.add(null);
				spAdapter.notifyDataSetChanged();
				showpagelable(curPage);
				//curPos = curPage;
				mViewPager.setCurrentItem(curPage);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			Logger.error("json error:"+e.getMessage());
		}   	
	}
	
	
	
	
	
	
	public void showpagelable(int position)
	{
		
		
		curPage = position;
		tv_pageshow.setText((curPage+1)+"/"+(pList.size()));
		
		if(curPage!=pList.size()-1)
		{
			tv_mmIntro.setScrollText(pList.get(position).getIntro());
			lly_botmintro.setVisibility(View.VISIBLE);
			tv_pageshow.setVisibility(View.VISIBLE);
			
			if(controller!=null)
			{
				umimg = new UMImage(mContext, pList.get(position).getImage());
				controller.setShareImage(umimg);
			}
			
		}else{
			lly_botmintro.setVisibility(View.GONE);
			tv_pageshow.setVisibility(View.GONE);
		}
		
		
		//tv_mmIntro.getline
		
		if(mSeekBar!=null&&pList!=null)
		{
			mSeekBar.setMax(pList.size());
			mSeekBar.setProgress((curPage+1));
			mSeekShow.setText((curPage+1)+"/"+(pList.size()));
		}				

	}
	
	private BroadcastReceiver onMeasureBroadcastReceiver = new BroadcastReceiver() 
	{
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(numlines==0)
			{
				numlines = tv_mmIntro.getSize();
				if(numlines<=1)
				{
					mMovieIntro.setText(tv_mmIntro.getScrollText());					
				}else{									
					mMovieIntro.setText(tv_mmIntro.getLineString(curLine));
				}
				tv_numline.setText((curLine+1)+"/"+numlines);				
			}
			
		}
		
	};

	

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
	    super.onConfigurationChanged(newConfig);
	     
	    if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
	    {
	        //Logger.info("ORIENTATION_LANDSCAPE");
	    }
	    if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
	    {
	    	//Logger.info("ORIENTATION_PORTRAIT");
	    }
	    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO)
	    {
	    	
	    }
	    else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES)
	    {
	    	
	    }
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		//Logger.info("onDestroy");
		mContext.unregisterReceiver(onMeasureBroadcastReceiver);
		super.onDestroy();
	}

	//记录书签
	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		if(historyid==0)
		{//插入
			
			HistoryBean hb = new HistoryBean();
			hb.setMovieid(Integer.parseInt(movieid));
			if(curPage==pList.size()-1)
			{
				hb.setMark(curPage-1);
			}else{
				hb.setMark(curPage);
			}
			
			hb.setMoviename(movieinfo.getName());
			hb.setSize(pList.size());
			hb.setAddtime(UtilsTools.getDate());
			historyid = DBHelper.getInstance(mContext).insertHistory(hb);
			hb = null;
		}else{
			//更新
			if(curPage==pList.size()-1)
			{
				DBHelper.getInstance(mContext).updateHistory(historyid, curPage-1,UtilsTools.getDate(),pList.size());
			}else
			{
				DBHelper.getInstance(mContext).updateHistory(historyid, curPage,UtilsTools.getDate(),pList.size());
			}			
		}
		
		super.onPause();
	}
	
	private SelectDialog selectDialog = null;
  	public void showDialog()
   	{
   	   	selectDialog = new SelectDialog(this,R.style.dialog,2);//创建Dialog并设置样式主题
   	   	Window win = selectDialog.getWindow();
   	   	LayoutParams params = new LayoutParams();
   	   	params.x = 0;//设置x坐标
   	   	params.y = 0;//设置y坐标
   	   	win.setAttributes(params);
   	   	selectDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
   	   	selectDialog.show(); 
   	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		MobclickAgent.onResume(this);
		super.onResume();
	}


	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		
		super.onStop();
	}
	
	
	public void getHistory()
	{
		//查询数据库
		Cursor cursor = DBHelper.getInstance(mContext).querySql("select * from history where movieid=?", new String[]{movieid});
		if(cursor!=null&&cursor.getCount()>0)
		{
			if(cursor.moveToFirst())
    		{
				//历史ID
				historyid = cursor.getInt(0);
				curPage = cursor.getInt(2);
				Logger.info("有历史记录"+historyid+"^^"+curPage);
    		}
		}else{
			Logger.info("没有历史记录");
			historyid = 0;
			curPage = 0;
		}
		if(cursor!=null)
			cursor.close();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
